package com.ssmIntegration.config;

import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import javax.sql.DataSource;

//@Configuration
public class MapperJavaConfig1 {

    /*
    sqlSessionFactory加入ioc容器
    mybatis -> sqlSessionFactoryBean加入ioc -> getObject() -> sqlSessionFactory
    方式1：外部指定mybatis-config.xml
    TODO：如果将dataSource和mybatis的组件配置到一起，出现@Value注解不生效的问题
          原因：mybatis的组件优先加载，spring的组件后加载，@Value还没加载到
          解决：分开配置，写到一个新的配置类中，写到DataSourceJavaConfig

     */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource) {

        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();

        // 指定配置文件等信息
        // 指定数据库连接池对象
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 指定外部mybatis配置文件
        Resource resource = new ClassPathResource("mybatis-config.xml");
        sqlSessionFactoryBean.setConfigLocation(resource);

        return sqlSessionFactoryBean;

    }

    /*
    mapper代理对象加入到ioc
    mapper代理对象的factoryBean，指定mapper接口存放的包。
    不需要再sqlSession.getMapper(xx.class)，直接找mapperScannerConfigurer即可
     */
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer() {
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.ssmIntegration.mapper");
        return mapperScannerConfigurer;
    }

}
